<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { userApi } from '@/modules/admin/manager/api'
import type {User,Role} from '@/modules/admin/manager/entity'
import { webSocketStore } from '@/modules/socket/stores/webSocket';
import { ElNotification } from 'element-plus'

const user = ref<User | null>(null)
const roles = ref<Role[]>([])
const error = ref<string | null>(null)
const wsSession = webSocketStore()

onMounted(async () => {
  wsSession.subMessage(
    '/admin/manager/user',
    (message: string) => {
      ElNotification({
        title: '你收到了消息',
        message: message,
        type: 'info',
      })
    }
  )
  try {
    const userId = 2;
    const userResponse = await userApi.getById(userId)
    if (userResponse.data && Object.keys(userResponse.data).length > 0) {
      user.value = userResponse.data
      try {
        const rolesResponse = await userApi.getRoles(userId)
        if (Array.isArray(rolesResponse.data)) {
          roles.value = rolesResponse.data
        } else {
          console.warn('获取到的角色数据不是数组')
        }
      } catch (roleErr) {
        console.error('获取角色失败', roleErr)
      }
    } else {
      error.value = '未找到用户信息'
    }
  } catch (err) {
    error.value = '获取用户数据失败'
    console.error(err)
  }
})

const formatDate = (date: Date | null) => {
  if (!date) return 'N/A'
  return new Date(date).toLocaleString()
}
</script>

<template>
  <div>
    <template v-if="$route.matched.length === 3">
      <main>
        <div v-if="error">{{ error }}</div>
        <div v-else-if="!user">加载中...</div>
        <div v-else>
          <h2>用户信息</h2>
          <p>用户ID: {{ user.id }}</p>
          <p>昵称: {{ user.name }}</p>
          <p>用户名: {{ user.username }}</p>
          <p>创建时间: {{ formatDate(user.createTime) }}</p>
          <p>更新时间: {{ formatDate(user.updateTime) }}</p>

          <h2>用户角色</h2>
          <ul v-if="roles.length">
            <li v-for="role in roles" :key="role.id">
              {{ role.name }} ({{ role.mark }})
            </li>
          </ul>
          <p v-else>该用户没有分配角色或获取角色失败</p>
        </div>
      </main>
    </template>
  </div>
</template>
